<?php

namespace App\Admin\Controllers;

use App\Admin\Services\GrantService;
use App\Admin\Traits\ReponseJson;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, ReponseJson;

    protected $admin;
    protected $vars = [];

    public function __construct()
    {
        // 未登入
        if (!auth('admin')->id()) {
            return;
        }

        // 管理员信息
        $this->admin = auth('admin')->user();
        // 根据路由配置获取菜单
        $menus = Cache::remember('admin:menus:' . auth('admin')->id(), 1, function () {
            $permissions = (new GrantService)->getRoutes($this->admin);
            $routes      = Route::getRoutes();
            $menus       = [];

            foreach ($routes as $route) {
                // 解析菜单
                if (
                    !isset($route->action['domain'])
                    || $route->action['domain'] != config('admin.route.domain')
                    || !isset($route->action['menu'])
                    || !$route->getName()
                ) {
                    continue;
                }

                // 判断权限
                if (!in_array('*', $permissions) && !in_array($route->getName(), $permissions)) {
                    continue;
                }

                [$group, $name] = explode(':', $route->action['menu'], 2);

                if (!isset($menus[$group])) {
                    $menus[$group] = [];
                }

                $menus[$group][] = [
                    'name'  => $name,
                    'url'   => broute($route->getName()),
                    'route' => $route->getName(),
                ];
            };

            return $menus;
        });

        // 模板赋值
        view()->share('_route_menus', $menus);
    }
}
